package com.kevin.permission.service;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.kevin.permission.common.RequestHolder;
import com.kevin.permission.dao.SysRoleMapper;
import com.kevin.permission.dao.SysRoleUserMapper;
import com.kevin.permission.exception.ParamsException;
import com.kevin.permission.model.SysRole;
import com.kevin.permission.model.SysRoleUser;
import com.kevin.permission.param.RoleParam;
import com.kevin.permission.util.BeanValidator;
import com.kevin.permission.util.IpUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    public void save(RoleParam param) {
        BeanValidator.check(param);
        if (checkExist(param.getName(),param.getId())){
            throw new ParamsException("角色名称已经存在");
        }
        SysRole role=SysRole.builder().name(param.getName()).status(param.getStatus()).type(param.getType())
                .remark(param.getRemark()).build();
        role.setOperator(RequestHolder.getCurrentUser().getUsername());
        role.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        role.setOperatorTime(new Date());
        sysRoleMapper.insertSelective(role);
    }

    public void update(RoleParam param) {
        BeanValidator.check(param);
        if (checkExist(param.getName(),param.getId())){
            throw new ParamsException("角色名称已经存在");
        }

        SysRole before=sysRoleMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before,"待更新角色不存在");

        SysRole after=SysRole.builder().id(param.getId()).name(param.getName()).status(param.getStatus()).type(param.getType())
                .remark(param.getRemark()).build();
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperatorTime(new Date());
        sysRoleMapper.updateByPrimaryKeySelective(after);
    }

    public List<SysRole> getAll() {
        return sysRoleMapper.getAll();
    }

    private boolean checkExist(String name, Integer id) {
        return sysRoleMapper.countByName(name,id) >0;
    }

    public List<SysRole> getRoleListByUserId(int userId) {
        List<Integer> roleIdList=sysRoleUserMapper.getRoleIdListByUserId(userId);
        if (CollectionUtils.isEmpty(roleIdList)){
            return Lists.newArrayList();
        }
        return sysRoleMapper.getByIdList(roleIdList);
    }

}
